﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using VitCode.Castle.Entities;
using VitCode.Castle.DataAccess;
using VitCode.Castle.Helper;
using VitCode.Web.UI.WebControls;
using Menu = VitCode.Castle.Entities.Menu;
using VitCode.Castle.Management;


namespace AMS.Web.BackStageManagement
{
    public partial class GroupMenu : Page
    {
        public string m_strGroupMenu = "";
        readonly CastleAccess m_Acc = new CastleAccess();
        BaseDataManager m_Help = new BaseDataManager();
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                if (Request.QueryString["CurrentRole"] != null)
                {
                    labelRoleId.Text = Request.QueryString["CurrentRole"].ToString();
                    ShowTree();
                }

            }
            TreeView_Menu.Attributes.Add("onclick", "CheckEvent(event)");
           // TreeView_Menu.Attributes.Add("onclick", "postBackByObject()");
        }

        public void ShowTree()
        {
            TreeView_Menu.Nodes.Clear();

            var node_0 = new TreeNode();
            node_0.ImageUrl = "../../Images/calendar.gif";
            node_0.Text = "AMS权限管理" + "<a herf='#'></a>";
            node_0.Value = "0";
            node_0.ExpandAll();
            node_0.SelectAction = TreeNodeSelectAction.Expand;
             
            TreeView_Menu.Nodes.Add(node_0);
            ViewState["ds"] = m_Acc.GetDataSetBySql("SELECT m.* FROM Frame_Menu m  where   1 = 1  and   m.ParentId is null ");
            var ds = (DataSet)ViewState["ds"];

            var dvTree = new DataView(ds.Tables[0]);


            foreach (DataRowView Row in dvTree)
            {
                var Node = new TreeNode();
                Node.Text = Row["Name"].ToString().Trim();
                Node.Value = Row["id"].ToString().Trim();

                var nameValueCollection = new NameValueCollection();
                nameValueCollection.Add("ResourceId", Row["id"].ToString().Trim());
                nameValueCollection.Add("ObjClassName", "Role");
                var lstObj = m_Acc.GetObjectList(new Permission().GetType().Name, nameValueCollection);
                if (lstObj != null && lstObj.Count > 0)
                {
                    for (int i = 0; i < lstObj.Count; i++)
                    {
                        var currentPerission = (Permission)lstObj[i];

                        Guid guidMenuId = currentPerission.ResourceId;
                        var objList = m_Acc.GetObjectList(new Menu().GetType().Name, "Id", guidMenuId.ToString());
                        if (objList != null && objList.Count > 0)
                        {
                            var currentMenu = (Menu)objList[0];
                            if (Node.Value == currentMenu.Id.ToString().Trim())
                            {
                                Node.Checked = true;
                            }
                        }
                    }
                }
                Node.ImageUrl = "../../Images/chart_bar.gif";
                node_0.ChildNodes.Add(Node);
                AddTree(Node.Value, Node);

            }

        }

        public void AddTree(String ParentID, TreeNode pNode)
        {
            IList obj = m_Acc.GetObjectList(new Menu().GetType().Name, "Parent", ParentID.Trim());
            if (obj != null && obj.Count > 0)
            {
                foreach (var list in obj)
                {
                    var Node = new TreeNode();
                    var currentmenu = (Menu)list;

                    Node.Value = currentmenu.Id.ToString().Trim();
                    Node.Text = currentmenu.Name.Trim() + "<a herf='#'></a>";
                    if (currentmenu.UrlPath.Trim().Length != 0)
                    {
                        Node.Text += "<font style='font-size: 11px' color='#808080'>[" + currentmenu.UrlPath.Trim() +
                                     "]</font> ";
                    }
                    if (currentmenu.Operate != null)
                    {
                        string[] strOperateList = currentmenu.Operate.Split(';');
                        for (int i = 0; i < strOperateList.Length; i++)
                        {
                            if (strOperateList[i].Length > 0)
                            {
                                TreeNode nodeChild = new TreeNode();
                                if (strOperateList[i] == "Add")
                                {
                                    nodeChild.Text = "新增";
                                    nodeChild.Value = "Add";
                                }
                                else if (strOperateList[i] == "Edit")
                                {
                                    nodeChild.Text = "修改";
                                    nodeChild.Value = "Edit";
                                }
                                else if (strOperateList[i] == "Delete")
                                {
                                    nodeChild.Text = "删除";
                                    nodeChild.Value = "Delete";
                                }
                                else if(strOperateList[i] == "LogicDelete")
                                {
                                    nodeChild.Text = "逻辑删除";
                                    nodeChild.Value = "LogicDelete";
                                }
                                else if (strOperateList[i] == "Audit")
                                {
                                    nodeChild.Text = "审核";
                                    nodeChild.Value = "Audit";
                                }
                              
                                else if (strOperateList[i] == "HandDepreciation")
                                {
                                    nodeChild.Text = "资产手动折旧";
                                    nodeChild.Value = "HandDepreciation";
                                }
                                else if (strOperateList[i] == "AutoDepreciation")
                                {
                                    nodeChild.Text = "资产自动折旧";
                                    nodeChild.Value = "AutoDepreciation";
                                }
                                else if (strOperateList[i] == "DataImport")
                                {
                                    nodeChild.Text = "数据导入";
                                    nodeChild.Value = "DataImport";
                                }
                                else if (strOperateList[i] == "ModuleDownLoad")
                                {
                                    nodeChild.Text = "模板下载";
                                    nodeChild.Value = "ModuleDownLoad";
                                }
                                Node.ChildNodes.Add(nodeChild);
                                nodeChild.Expanded = true;
                                nodeChild.ImageUrl = "../../Images/notes.gif";

                                var nameValueCollection2 = new NameValueCollection();
                                nameValueCollection2.Add("ObjId", labelRoleId.Text.Trim());
                                nameValueCollection2.Add("ObjClassName", "Role");
                                nameValueCollection2.Add("ResourceId", currentmenu.Id.ToString());
                                var listObj2 = m_Acc.GetObjectList(new Permission().GetType().Name, nameValueCollection2);
                                if (listObj2 != null && listObj2.Count > 0)
                                {
                                    var currentPermission2 = (Permission)listObj2[0];
                                    if (currentPermission2.OperateNum != null && currentPermission2.OperateNum.Contains(strOperateList[i]))
                                        nodeChild.Checked = true;
                                }
                            }
                        }
                    }
                    var nameValueCollection = new NameValueCollection();
                    nameValueCollection.Add("ObjId", labelRoleId.Text.Trim());
                    nameValueCollection.Add("ObjClassName", "Role");
                    var listObj = m_Acc.GetObjectList(new Permission().GetType().Name, nameValueCollection);
                    if (listObj != null && listObj.Count > 0)
                    {
                        for (int i = 0; i < listObj.Count; i++)
                        {
                            var currentPermission = (Permission)listObj[i];

                            Guid guidMenuId = currentPermission.ResourceId;
                            var objList = m_Acc.GetObjectList(new Menu().GetType().Name, "Id", guidMenuId.ToString());
                            if (objList != null && objList.Count > 0)
                            {
                                Menu currentMenu = (Menu)objList[0];
                                if (Node.Value == currentMenu.Id.ToString().Trim())
                                {
                                    Node.Checked = true;
                                }
                            }
                        }
                    }
                    pNode.ChildNodes.Add(Node);
                    Node.ImageUrl = "../../Images/notes.gif";
                    AddTree(currentmenu.Id.ToString().Trim(), Node); //再次递归

                }
            }
        }

        /// <summary>
        ///调用自身函数循环遍历TreeView
        /// </summary>
        /// <param name="node"></param>
        /// <returns>返回FunctionString字符串</returns>
        public Dictionary<string, string> GetTreeCheck(TreeNodeCollection treeNodeCollection)
        {
            Dictionary<string, string> mDictionary = new Dictionary<string, string>();
            foreach (TreeNode node in treeNodeCollection)
            {
               if(node.Checked)
               {
                   string key = node.Value;
                   mDictionary.Add(key,"");
               }
                foreach (TreeNode treenode in node.ChildNodes)
                {
                    if (treenode.Checked)
                    {

                        string key = treenode.Value;
                        string value = "";
                        foreach (TreeNode childnode in treenode.ChildNodes)
                        {
                            if (childnode.Checked)
                            {
                                value += childnode.Value + ";";
                            }
                        }
                        if (value.Length > 0)
                            value = value.Substring(0, value.Length - 1);
                        mDictionary.Add(key, value);
                    }

                }
            }
          

            return mDictionary;

        }


        ///// <summary>
        ///// 当点击选择框时执行的事件
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //protected void TreeView_Menu_TreeNodeCheckChanged(object sender, TreeNodeEventArgs e)
        //{
        //    SetChildChecked(e.Node);
        //    SetParentChecked(e.Node);
        //}

        ///// <summary>
        ///// 选择所有的父目录
        ///// </summary>
        ///// <param name="parentNode"></param>
        //private void SetChildChecked(TreeNode parentNode)
        //{
        //    foreach (TreeNode node in parentNode.ChildNodes)
        //    {
        //        node.Checked = parentNode.Checked;

        //        if (node.ChildNodes.Count > 0)
        //            SetChildChecked(node);
        //    }
        //}

        ///// <summary>
        ///// 选择所有的子目录
        ///// </summary>
        ///// <param name="childNode"></param>
        //private void SetParentChecked(TreeNode childNode)
        //{
        //    if (childNode.Parent != null)
        //    {
        //        if (childNode.Checked)
        //        {
        //            childNode.Parent.Checked = true;
        //        }
        //        SetParentChecked(childNode.Parent);
        //    }


        //}
        protected void Button_Cancel_Click(object sender, EventArgs e)
        {

            Window.Close();
        }




        protected void btn_Submit_Click(object sender, EventArgs e)
        {
            Dictionary<string, string> mDictionary = GetTreeCheck(TreeView_Menu.Nodes[0].ChildNodes);

            var nameValueCollection = new NameValueCollection();
            nameValueCollection.Add("ObjId", labelRoleId.Text.Trim());
            nameValueCollection.Add("ObjClassName", "Role");
            var lstObj = m_Help.GetObjectList(new Permission().GetType().Name, nameValueCollection);
            if (lstObj != null && lstObj.Count > 0)
            {
                for (int i = 0; i < lstObj.Count; i++)
                {
                    var currentPerission = (Permission)lstObj[i];
                    m_Help.Delete(currentPerission);
                }
            }

            foreach (var collection in mDictionary)
            {
                string strMenuId = collection.Key.Trim();
                string strOperate = collection.Value.Trim();
          
                Permission objPerission = new Permission();
                Guid guidRoleId = new Guid(labelRoleId.Text.Trim());
                Guid guidMenuId = new Guid(strMenuId);
                objPerission.ObjId = guidRoleId;
                objPerission.ResourceId = guidMenuId;
                objPerission.ObjClassName = "Role";
                objPerission.ResourceClassName = "Menu";
                objPerission.OperateNum = strOperate;
                m_Help.SaveOrUpdate(objPerission);
            }
            Alert.MessageBox("设置成功!");
        }

     
    }
}
